package com.likerSai;

import com.likerSai.util.ListNode;

/**
 * 2两数相加
 *
 * @author sun.ye
 * @since 2021-04-21 17:37
 */
public class AddTwoNumbers {


    public static void main(String[] args) {
        ListNode l1 = new ListNode(5);
//        l1 = new ListNode(4,l1);
//        l1 = new ListNode(2,l1);
        ListNode l2 = new ListNode(5);
//        l2 = new ListNode(6,l2);
//        l2 = new ListNode(5,l2);
//      [2,4,3]
//		[2,5,6,4]
        ListNode result =  addTwoNumbers(l1,l2);
        System.out.println(result);
    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        if (l1.next == null && l2.next == null){
            if(l1.val + l2.val <= 9){
                return new ListNode(l1.val + l2.val);
            }
        }
        ListNode result = new ListNode();
        ListNode pre = new ListNode(-1);

        int add = 0;
        boolean endFlag = false;
        while(!endFlag){

            int a = l1 == null ? 0 : l1.val;
            int b = l2 == null ? 0 : l2.val;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;


            int sum = a + b + add;
            if(sum > 9){
                sum -= 10;
                add = 1;
            }else {
                add = 0;
            }
            endFlag = l1 == null && l2 == null && add == 0;
            ListNode curr = new ListNode(sum);
            if(pre.val == -1){
                pre.val = sum;
                result = pre;
            }else {
                pre.next = curr;
                pre = curr;
            }
        }



        return result;
    }


}

